package com.lakeworks.framework.web.service;

import com.lakeworks.common.core.domain.entity.SysUser;
import com.lakeworks.common.exception.response.ResponseException;
import com.lakeworks.common.utils.DateUtils;
import com.lakeworks.common.utils.ServletUtils;
import com.lakeworks.common.utils.ip.IpUtils;
import com.lakeworks.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.lakeworks.common.constant.Constants.LOGIN_SUCCESS;
import static com.lakeworks.common.enums.UserStatus.DISABLE;
import static com.lakeworks.common.utils.MessageUtils.message;
import static com.lakeworks.framework.manager.AsyncManager.me;
import static com.lakeworks.framework.manager.factory.AsyncFactory.recordLogininfor;
import static java.lang.String.format;

/**
 * 登录校验方法
 *
 * @author lakeworks
 */
@Component
public class SysLoginService {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysUserService userService;

    /**
     * 微信
     */
    public String wechatLogin(SysUser user,String openId) {
        if (user == null)
            throw new ResponseException(format("登录用户[%s]不存在",user.getNickName()));
        if (DISABLE.getCode().equals(user.getStatus()))
            throw new ResponseException(format("对不起，您的账号[%s]已停用",user.getNickName()));

        me().execute(recordLogininfor(user.getNickName(), LOGIN_SUCCESS, message("user.login.success")));
        recordLoginInfo(user.getUserId());

        return tokenService.createToken(user,openId);
    }

    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }
}
